//
//  OpenInterventoViewController.m
//  InterventixApp
//
//  Created by Diego Falcinelli on 15/05/13.
//
//

#import "OpenInterventoViewController.h"
#import "Syncronize.h"
#import "Utente.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "Define.h"
#import "JsonCR2.h"
#import "ComunicationsUtils.h"
#import "DettagliInterventoViewController.h"
#import "FirmaInterventoViewController.h"
#import "CostiInterventoViewController.h"
#import "ClientiInterventoViewController.h"
#import "Buffer.h"
#import "Syncronize.h"
#import "CoreDataManager.h"
#import "ManagedObjectCloner.h"
#import "Util.h"
#import "InfoClienteViewController.h"

@interface OpenInterventoViewController ()

@end

@implementation OpenInterventoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)viewDidLoad{
    [super viewDidLoad];
    
    
    self.mail = false;
    self.closer = false;
    
    self.array = [NSMutableArray arrayWithCapacity:0];
    [self.array addObject:@"Cliente"];
    [self.array addObject:@"Tecnico"];
    [self.array addObject:@"Informazioni"];
    [self.array addObject:@"Dettagli"];
    [self.array addObject:@"Costi"];
    [self.array addObject:@"Firma"];
    
    if([self.intervento.saldato isEqual: @0]){
        [self.saldaBtn setTintColor:[UIColor redColor]];
        self.saldaBtn.title = @"Salda";
    }else{
        [self.saldaBtn setTintColor:[UIColor blackColor]];
        self.saldaBtn.title = @"Pagato";
    }
    
    [Util lockBuffer];
    
}
- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}


-(void ) viewWillAppear:(BOOL)animated{
    if([[self.coreDataManager calcStatusIntervento:self.intervento] isEqualToString:@"NEW"]) {
        self.sendMailBtn.enabled = false;
    }else{
        self.sendMailBtn.enabled = true;
    }
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewDidAppear:(BOOL)animated{
        //NSLog(@"OpenInterventoViewController : %llu == %llu",self.hashInter,[CoreDataManager hashcodeIntervento:self.intervento]);
    [self.table reloadData];
}

-(BOOL) complete{
    return [self.coreDataManager checkIntervento:self.intervento];
}

-(IBAction) indietro{
    if([self complete] == false){
        
        UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Attenzione"
                                                              message:@"L'intervento risulta incompleto.Annullare la modifica oppure completare?"
                                                             delegate:self
                                                    cancelButtonTitle:@"Annulla"
                                                    otherButtonTitles:@"Completa", nil];
        [myAlertView setAlertViewStyle:UIAlertViewStyleDefault];
        [myAlertView show];
    }else{
        if([CoreDataManager hashcodeIntervento:self.intervento] != self.hashInter){
            self.save = true;
            
            UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Salva"
                                                                  message:@"L'intervento risulta modificato. Inviare le modifiche?"
                                                                 delegate:self
                                                        cancelButtonTitle:@"Esci"
                                                        otherButtonTitles:@"Invia", nil];
            [myAlertView setAlertViewStyle:UIAlertViewStyleDefault];
            [myAlertView show];
        }else{
            [[self navigationController] popViewControllerAnimated:YES];
        }
    }
}

-(IBAction) sendMailAction{
    self.mail = true;
    UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Invia Mail"
                                                          message:@"Email del cliente, oppure modificare per inviare ad un altro destinatario." delegate:self cancelButtonTitle:@"Annulla" otherButtonTitles:@"Invia", nil];
    [myAlertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [myAlertView textFieldAtIndex:0].font =[UIFont systemFontOfSize:13];
    [myAlertView textFieldAtIndex:0].text = self.intervento.cliente.email;
    [myAlertView show];
}


-(IBAction) close{
    self.closer = true;
    UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Chiudi Intervento?"
                                                          message:@"Chiudendo l'intervento non sarà più visibile" delegate:self cancelButtonTitle:@"Annulla" otherButtonTitles:@"Chiudi", nil];
    [myAlertView show];
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1){
        if(self.mail){
            self.sendMailBtn.title = @"Invio in corso...";
            NSLog(@"send mail to: %@",[[alertView textFieldAtIndex:0]text]);
            [self sendMail:[[alertView textFieldAtIndex:0]text]];
        }
        if(self.closer){
            NSLog(@"set close intervent : true");
        }
        if (self.save) {
            // Invia le modifiche nel buffer
            // salvando tutto il contesto
            self.intervento.buffer = @1;
            [self.coreDataManager save];
            [[self navigationController] popViewControllerAnimated:YES];
        }
    }
    if (buttonIndex == 0){
        if (self.save || [self complete] == false) {
            // Annulla le modifiche e ristablisce i dati originali all'interno dei oggetti
            
            // Refresh del cliente o delete se nuovo
            if(self.intervento.cliente!=nil){
                if([self.intervento.cliente.idcliente intValue] > 0){
                    [self.coreDataManager refresh:self.intervento.cliente];
                    NSLog(@"Refresh Cliente");
                }else{
                    [self.coreDataManager deleteObject:self.intervento.cliente];
                    NSLog(@"Delete Cliente Nuovo");
                }
            }
            
            // Refresh dell'intervento o delete se nuovo
            if([self.intervento.idintervento intValue]>0){
              [self.coreDataManager refresh:self.intervento];
                 NSLog(@"Refresh Intervento");
            }
            else {
                [self.coreDataManager deleteObject:self.intervento];
                 NSLog(@"Delete Intervento Nuovo");
            }
            
            [[self navigationController] popViewControllerAnimated:YES];
        }
    }
    self.mail = false;
    self.closer = false;
}


-(void) sendMail:(NSString *) mail{
    // Syncro clienti
    NSMutableDictionary *diz2 = [[NSMutableDictionary alloc]initWithCapacity:0];
    [diz2 setObject:self.intervento.idintervento forKey:@"idintervento"];
    NSMutableArray * mails = [[NSMutableArray alloc] initWithCapacity:0];
    [mails addObject:mail];
    [diz2 setObject:mails forKey:@"email"];
    NSString * json_req2 = [JsonCR2 createRequest:@"interventions" action:@"email" paramters:diz2 iduser:self.user.idutente];
    ASIFormDataRequest * request2 = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:[ComunicationsUtils getUrl]]];
    [request2 setDelegate:self];
    [request2 setPostValue:json_req2 forKey:@"DATA"];
    [request2 startAsynchronous];
}

-(IBAction) salda{
    if([self.intervento.saldato isEqual: @0]){
        self.intervento.saldato = @1;
        [self.saldaBtn setTintColor:[UIColor blackColor]];
        self.saldaBtn.title = @"Pagato";
        
    }else{
        self.intervento.saldato = @0;
        [self.saldaBtn setTintColor:[UIColor redColor]];
        self.saldaBtn.title = @"Salda";
    }
    
}





- (void)requestFinished:(ASIHTTPRequest *)request
{
    //Leggo il risutato della richiesta
    NSDictionary *json = [JsonCR2 read:[request responseString]];
    NSString *response = [json objectForKey:@"response"];
    NSDictionary *req = [json objectForKey:@"request"];
    NSString *section = [req objectForKey:@"section"];
    NSString *action = [req objectForKey:@"action"];
    NSLog(@"REQ_END: {section: %@, action: %@}",section,action);
    
    
    if([response isEqualToString:@"success"]){
        // Syncro Clients
        if([section isEqualToString:@"interventions"] && [action isEqualToString:@"email"] ){
            NSLog(@"Mail Inviata!!!");
            self.sendMailBtn.title = @"Invia mail";
        }
    }else{
        
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",[error description]);
}





// TABELLA

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.array count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if([self.intervento.idintervento intValue]<0)return @"Nuovo Intervento";
	return [NSString stringWithFormat: @"Intervento %@",self.intervento.numero];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    [cell setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:1]];
    
    NSString *name = [self.array objectAtIndex:indexPath.row];
    if([name isEqual:@"Cliente"]){
        cell.textLabel.text = name;
        cell.detailTextLabel.text = self.intervento.cliente.nominativo;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        if([[self.coreDataManager calcStatusCliente:self.intervento.cliente] isEqualToString:@"MOD"] || [[self.coreDataManager calcStatusCliente:self.intervento.cliente] isEqualToString:@"NEW"] ){
            [Util setCellModified:cell];
        }
    }
    else if([name isEqual:@"Tecnico"]){
        cell.textLabel.text =  name;
        cell.detailTextLabel.text =  [NSString stringWithFormat:@"%@ %@", self.intervento.tecnico.nome, self.intervento.tecnico.cognome];
        [cell setBackgroundColor:[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1]];
    }
    else if([name isEqual:@"Dettagli"]){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        [cell setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:1]];
        cell.textLabel.text = name;
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%d dett",[self.intervento.dettagli count]];
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    else if([name isEqual:@"Costi"]){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        [cell setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:1]];
        cell.textLabel.text = name;
        
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2f €",[self.intervento.totale floatValue]];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    else if([name isEqual:@"Firma"]){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        if(self.intervento.firma.length > 0){
            [cell setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:1]];
        }else{
            [Util setCellAlert:cell];
        }
        cell.textLabel.text = name;
        
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",[NSByteCountFormatter stringFromByteCount:self.intervento.firma.length countStyle:NSByteCountFormatterCountStyleDecimal]];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }else if([name isEqualToString:@"Informazioni"]){
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"dd/MM/yyyy HH:mm"];
        NSString *dateString = [dateFormatter stringFromDate:self.intervento.dataora];
        cell.detailTextLabel.text = dateString;
        cell.textLabel.text = name;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    else{
        cell.textLabel.text = name;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return cell;
}



// CellHeight
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 50;
}



// SWIPE ROW
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return YES if you want the specified item to be editable.
    NSString *name = [self.array objectAtIndex:indexPath.row];
    if([name isEqual:@"Cliente"]){
        return YES;
    }else{
        return NO;
    }
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Tap Pulsante di swipe
        // Controllo del cliente
        if([[self.coreDataManager calcStatusCliente:self.intervento.cliente] isEqualToString:@"SAVE"]){
            // Lista dei clienti
            ClientiInterventoViewController *open = [self.storyboard instantiateViewControllerWithIdentifier:@"ClientiInterventoViewController"];
            open.intervento = self.intervento;
            open.user = self.user;
            open.coreDataManager = self.coreDataManager;
            [self.navigationController pushViewController:open animated:YES];
        }else{
            // Dettaglio del Cliente
            ClientiInterventoViewController *open = [self.storyboard instantiateViewControllerWithIdentifier:@"ClientiInterventoViewController"];
            open.intervento = self.intervento;
            open.user = self.user;
            open.coreDataManager = self.coreDataManager;
            [self.navigationController pushViewController:open animated:NO];
            
            InfoClienteViewController *open2 = [self.storyboard instantiateViewControllerWithIdentifier:@"InfoClienteViewController"];
            open2.intervento = self.intervento;
            open2.cliente = self.intervento.cliente;
            open2.clienteSelect = nil;
            open2.coreDataManager = self.coreDataManager;
            open2.user = self.user;
            open2.hashCLient = [CoreDataManager hashcodeCliente:self.intervento.cliente];
            [self.navigationController pushViewController:open2 animated:YES];
        }
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"Modifica";
}
// END SWIPE ROW


// CLICK
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *name = [self.array objectAtIndex:indexPath.row];
    if([name isEqual:@"Cliente"]){
        // Controllo se il cliente e null
        // aprendo la lista dei clienti
        if([[self.coreDataManager calcStatusCliente:self.intervento.cliente] isEqualToString:@"NULL"]){
            // Lista dei clienti
            ClientiInterventoViewController *open = [self.storyboard instantiateViewControllerWithIdentifier:@"ClientiInterventoViewController"];
            open.intervento = self.intervento;
            open.user = self.user;
            open.coreDataManager = self.coreDataManager;
            [self.navigationController pushViewController:open animated:YES];
        }
        
    }
    if([name isEqual:@"Informazioni"]){
        OpenInterventoViewController *open = [self.storyboard instantiateViewControllerWithIdentifier:@"InfoInterventoViewController"];
        open.intervento = self.intervento;
        open.user = self.user;
        open.coreDataManager = self.coreDataManager;
        [self.navigationController pushViewController:open animated:TRUE];
    }
    if([name isEqual:@"Dettagli"]){
        DettagliInterventoViewController *open = [self.storyboard instantiateViewControllerWithIdentifier:@"DettagliInterventoViewController"];
        open.intervento = self.intervento;
        open.user = self.user;
        open.coreDataManager = self.coreDataManager;
        [self.navigationController pushViewController:open animated:TRUE];
    }
    if([name isEqual:@"Firma"]){
        FirmaInterventoViewController *open = [self.storyboard instantiateViewControllerWithIdentifier:@"FirmaInterventoViewController"];
        open.intervento = self.intervento;
        open.user = self.user;
        open.coreDataManager = self.coreDataManager;
        [self.navigationController pushViewController:open animated:TRUE];
    }
    if([name isEqual:@"Costi"]){
        CostiInterventoViewController *open = [self.storyboard instantiateViewControllerWithIdentifier:@"CostiInterventoViewController"];
        open.intervento = self.intervento;
        open.user = self.user;
        open.coreDataManager = self.coreDataManager;
        [self.navigationController pushViewController:open animated:TRUE];
    }
}




@end
